package com.ndp.fb.fbagent.service.impl.paramadapter;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.annotation.FBParam;
import com.ndp.fb.constant.ConfigConst;
import com.ndp.fb.fbagent.service.jsonmapper.FbParamJsonMapper;
import com.ndp.fb.model.fbagent.param.AttachmentParam;
import com.ndp.fb.model.fbagent.param.CallBackModel;
import com.ndp.fb.model.fbagent.param.FacebookParam;
import com.ndp.fb.util.ArrayUtil;
import com.restfb.BinaryAttachment;
import com.restfb.JsonMapper;
import com.restfb.Parameter;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by infi on 2015/1/21.
 */
public class FacebookParamAdapter {

    private JsonMapper jsonMapper = new FbParamJsonMapper();

    public List adapterParam(FacebookParam param) {
        return adapterParam(param, true);
    }

    /**
     * 第二个参数判断是否处理AttachmentParam中的文件，如果是断点续传的话，默认不用处理。 应该从nfs上下载一部分，然后在传递一部分
     *
     * @param param
     * @param isAdapterAttachmentParam
     * @return
     */
    public List adapterParam(FacebookParam param, boolean isAdapterAttachmentParam) {
        List list = new ArrayList();
        if (param instanceof AttachmentParam) {
            if (isAdapterAttachmentParam) { //需要对文件进行处理
                AttachmentParam fileParam = (AttachmentParam) param;
                String nfsFilePath = ((AttachmentParam) param).getNfsFilePath();
                byte[] fileBytes = ArrayUtil.getByteByUrl(nfsFilePath);
                list.add(BinaryAttachment.with(fileParam.getFileName(), fileBytes));
            }
        } //需要放掉else，如果AttachmentParam增加了一些额外的参数
        {
            Class inputClass = param.getClass();
            while (inputClass != null) {
                Field[] fields = inputClass.getDeclaredFields();
                for (Field field : fields) {
                    Annotation[] anns = field.getDeclaredAnnotations();
                    for (Annotation anno : anns) {
                        if (anno instanceof FBParam) {
                            try {
                                StringBuffer methodName = new StringBuffer();
                                String firstChar = field.getName().substring(0, 1)
                                        .toUpperCase(Locale.getDefault());
                                String otherChar = field.getName().substring(1);
                                if (field.getType().isAssignableFrom(boolean.class)) {
                                    methodName.append("is");
                                } else {
                                    methodName.append("get");
                                }
                                methodName.append(firstChar);
                                methodName.append(otherChar);
                                Method method = inputClass.getMethod(methodName
                                        .toString());
                                Object fieldValue = method.invoke(param);
                                String fieldName = ((FBParam) anno).value();
                                if (null != fieldValue) {
                                    String jsonValue;
                                    if (fieldValue.getClass().isPrimitive()) {
                                        jsonValue = fieldValue.toString();
                                    } else {
                                        jsonValue = jsonMapper.toJson(fieldValue, true);
                                    }
//                                    if ("batch".equals(fieldName)) {
//                                        list.add(Parameter.with(fieldName, jsonValue));
//                                    } else {
//                                        list.add(Parameter.with(fieldName, jsonValue));
//                                    }
                                    if(param.getRemoveAccountFromUrl() != null &&  param.getRemoveAccountFromUrl() && "account_id".equals(fieldName))
                                        System.out.print("1");
                                    else
                                        list.add(Parameter.with(fieldName, jsonValue));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                inputClass = inputClass.getSuperclass();
            }
        }

        //账号
        if (null != param.getFbAccountId()) {
            list.add(Parameter.with(ConfigConst.FB_URL_PARAM_EXT_PARAM_FBACCOUNTID, param.getFbAccountId()));
        }

        if (null != param.getApiPriorityCode()) {
            list.add(Parameter.with(ConfigConst.FB_URL_PARAM_EXT_PARAM_API_PRIORITY, param.getApiPriorityCode()));
        }
        if (param.getResultClassName()!= null) {
            list.add(Parameter.with(ConfigConst.FB_URL_PARAM_EXT_PARAM_RESULT_CLASS, param.getResultClassName()));
        }

        //回调
        if (param.getCallBack() != null && param.getCallBack()) {
            CallBackModel callBackModel = new CallBackModel();
            callBackModel.setTarget(param.getApiCallbackTargetType());
            callBackModel.setEquipment(param.getEquipment());
            list.add(Parameter.with(ConfigConst.FB_URL_PARAM_EXT_PARAM_CALL_BACK, JSON.toJSONString(callBackModel)));
        }
        return list;
    }


}
